package com.gcb.framework.web.service;

import com.gcb.common.constant.CacheConstants;
import com.gcb.common.constant.Constants;
import com.gcb.common.constant.UserConstants;
import com.gcb.common.core.domain.entity.SysUser;
import com.gcb.common.core.redis.RedisCache;
import com.gcb.common.enums.LoginType;
import com.gcb.common.exception.ServiceException;
import com.gcb.common.exception.user.BlackListException;
import com.gcb.common.exception.user.CaptchaException;
import com.gcb.common.exception.user.CaptchaExpireException;
import com.gcb.common.exception.user.UserPasswordNotMatchException;
import com.gcb.common.utils.DateUtils;
import com.gcb.common.utils.MessageUtils;
import com.gcb.framework.model.LoginUser;
import com.gcb.framework.utils.SecurityUtils;
import com.gcb.common.utils.StringUtils;
import com.gcb.common.utils.ip.IpUtils;
import com.gcb.framework.manager.AsyncManager;
import com.gcb.framework.manager.factory.AsyncFactory;
import com.gcb.framework.security.context.AuthenticationContextHolder;
import com.gcb.framework.security.custom.UsernamePhoneAuthenticationToken;
import com.gcb.framework.mapper.SysUserRoleMapper;
import com.gcb.framework.service.ISysConfigService;
import com.gcb.framework.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.regex.Pattern;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 登录验证
     *
     * @param username  账号
     * @param password  密码
     * @param code      验证码
     * @param uuid      唯一标识
     * @param loginType 登录类型 0账号密码登录  1短信登录
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid, String loginType) {
        boolean isPassword = false;
        //在判断是密码还是验证码登录 默认账号密码登录
        if (StringUtils.isBlank(loginType) || LoginType.ACCOUNT.getCode().equals(loginType)) {
            if (StringUtils.isBlank(password)) {
                throw new ServiceException("用户密码不能为空");
            }
            // 图片验证码校验
            validateCaptcha(username, code, uuid);
            // 登录前置校验
            loginPreCheck(username, password);
            isPassword = true;
        } else if (LoginType.SMS.getCode().equals(loginType)) {
            // 短信验证码校验
            sysValidateVerifyCode(username, code);
        } else {
            throw new ServiceException("请选择正确的登录方式");
        }
        // 用户验证
        return loginCheckDetail(isPassword, username, password, loginType);
    }

    /**
     * 后台登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 密码为空 错误
        if (StringUtils.isEmpty(password)) {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
////            throw new UserNotExistsException();
            throw new ServiceException("密码不能为空");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    public String loginCheckDetail(boolean isPassword, String username, String password, String loginType) {
        Authentication authentication = null;
        try {
            if (isPassword) {
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
                AuthenticationContextHolder.setContext(authenticationToken);
                // 该方法会去调用 UserDetailsServiceImpl.loadUserByUsername
                authentication = authenticationManager.authenticate(authenticationToken);
            } else {
                // 该方法会去调用 UserDetailsByPhoneServiceImpl.loadUserByUsername
                authentication = authenticationManager.authenticate(new UsernamePhoneAuthenticationToken(username));
            }
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验图形验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 后台验证码登录-校验验证码
     *
     * @param phone 电话
     * @param code  验证码
     */
    public void sysValidateVerifyCode(String phone, String code) {
        if (!Pattern.compile("^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$").matcher(phone).matches()) {
            throw new ServiceException("手机号格式错误");
        }
        String verifyKey = CacheConstants.SYS_VERIFY_CODE_KEY + StringUtils.nvl(phone, "");
        Long expireTime = redisCache.getExpire(verifyKey);
        if (expireTime != null && expireTime.longValue() > 0) {
            String verifyCode = redisCache.getCacheObject(verifyKey);
            if (StringUtils.isBlank(verifyCode)) {
                throw new ServiceException("系统错误，请重新发送验证码");
            }
            if (!code.equalsIgnoreCase(verifyCode)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, MessageUtils.message("user.smscode.error")));
                throw new ServiceException("验证码错误");
            }
        } else {// 缓存过期
            throw new ServiceException("此验证码已过期，请重新发送验证码");
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    @Transactional
    public String toggleDept(Long userId, Long deptId) {
        //根据userId和deptId查询sys_user_role 如果无记录则无法切换
        int i = userRoleMapper.countByUserIdAndDeptId(userId, deptId);
        if (i == 0) {
            throw new ServiceException("账号暂无该部门信息");
        }
        //如果存在对应记录则 更新sys_user中deptId（当前部门id）
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setDeptId(deptId);
        sysUser.setUpdateBy(SecurityUtils.getUsername());
        userService.updateUserProfile(sysUser);
        SysUser user = userService.selectUserById(userId);
        //重新登录 将新用户信息加载到Security中
        return loginCheckDetail(false, user.getPhonenumber(), null, null);
    }
}
